package com.atguigu.day2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareData {
    //约定flag标志位 flag=1--->A
    private int flag = 1;
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void print5() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (flag != 1) {
                condition1.await();
            }
            //干活
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            //通知
            flag = 2;
            condition2.signal();
        } finally {
            lock.unlock();
        }

    }

    public void print10() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (flag != 2) {
                condition2.wait();
            }
            //干活
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            //通知
            flag = 3;
            condition3.signal();
        } finally {
            lock.unlock();
        }

    }

    public void print15() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (flag != 3) {
                condition3.wait();
            }
            //干活
            for (int i = 0; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            //通知
            flag = 1;
            condition1.signal();
        } finally {
            lock.unlock();
        }

    }
}

public class ThreadOrderAccess {
    /*
     *  * 线程间定制化调用通信
     *
     *  * 多线程之间按顺序调用，实现A->B->C
     *  * 三个线程启动，要求如下：
     *  *
     *  * AA打印5次，BB打印10次，CC打印15次
     *  * 接着
     *  * AA打印5次，BB打印10次，CC打印15次
     *  * ......来10轮*/


    /*
     *1、高内低耦前提下： 线程 操作 资源
     *2、线程间通信： 判断   干活   通知
     *3、多线程通信中，如果存在wait方法的调用要避免-----虚假唤醒
     *4、通知  判断  标志位
     * */
    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread(() -> {
            try {
                shareData.print5();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "AA").start();
        new Thread(() -> {
            try {
                shareData.print10();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "BB").start();
        new Thread(() -> {
            try {
                shareData.print15();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "CC").start();
    }

}
